// UDPServer.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <iostream>
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
	WSADATA wsaData;
	WORD wVersion = MAKEWORD(2, 2);
	// WSA Startup
	if (WSAStartup(wVersion, &wsaData))
	{
		cout << "WSA Startup error: " << WSAGetLastError() << endl;
	}
	else
	{
		cout << "WSA Startup success" << endl;
	}

	// socket
	SOCKET reciver;
	reciver = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	cout << "Socket created" << endl;

	// bind
	SOCKADDR_IN reciverAddress;
	reciverAddress.sin_family = AF_INET;
	reciverAddress.sin_port = htons(8888);
	reciverAddress.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
	int reciverAddressLen;
	if (bind(reciver, (SOCKADDR*)&reciverAddress, sizeof(reciverAddress)))
	{
		cout << "Bind error: " << WSAGetLastError() << endl;
	}
	else
	{
		cout << "Bind success" << endl;
		
		//reciver
		int reciverBufLen = 1000;
		char *reciverBuf = new char[reciverBufLen];
		int reciverFlags = 0;
		int reciverBytes;
		do {
			reciverBytes = recvfrom(reciver, reciverBuf, reciverBufLen, reciverFlags, (SOCKADDR*)&reciverAddress, &reciverAddressLen);
			if (reciverBytes == SOCKET_ERROR)
			{
				cout << "Reciver error: " << WSAGetLastError() << endl;
			}
			else
			{
				cout << "Reciver success: " << reciverBytes << " bytes" << endl;
				reciverBuf[reciverBytes] = '\0';
				cout << reciverBuf << endl;
			}
		} while (reciverBytes == SOCKET_ERROR);
	}
	// close reviver socket
	if (closesocket(reciver) == SOCKET_ERROR)
	{
		cout << "Close reciver socket error: " << WSAGetLastError() << endl;
	}
	else
	{
		cout << "Reciver socket closed" << endl;
	}
	// WSA Cleanup
	if (WSACleanup())
	{
		cout << "WSA Cleanup error: " << WSAGetLastError() << endl;
	}
	else
	{
		cout << "WSA Cleanup success" << endl;
	}
	return 0;
}

